package com.zwj.gulimall.product.exception;

import com.zwj.common.utils.R;
import com.zwj.common.exception.GuliMallAdviceEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName GuliMallUnityExceptionAdvice
 * @Description TODO
 * Author zwJ
 * Date 2020/8/16 16:32
 * Version 1.0
 **/
@Slf4j
@RestControllerAdvice(basePackages = "com.zwj.gulimall.product.controller")
public class GuliMallUnityExceptionAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleParamValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现异常 异常问题{} 异常类型{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Map<String, String> errMap = new HashMap();
        fieldErrors.forEach(fieldError -> {
            errMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(GuliMallAdviceEnum.PARAM_VERIFY_EXCEPTION).put("data", errMap);
    }

}
